package com.vq3.digitalizationsoftwareintegrates.Utils.ExceptionHandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.vq3.digitalizationsoftwareintegrates.Entity.Info.ResultInfo;
import com.vq3.digitalizationsoftwareintegrates.Utils.PackagedDataUtil.Impl.PackagedDataImpl;
import com.vq3.digitalizationsoftwareintegrates.Utils.PackagedDataUtil.PackagedData;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;



//TODO 一定记得用日志文件记录下来错误信息！！！！！！！
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        ResultInfo resultInfo = new ResultInfo();
        PackagedData packagedData = new PackagedDataImpl();
        resultInfo.setFlag(false);
        if (exception instanceof BadCredentialsException) {
            resultInfo.setErrorMsg("账户或密码错误！");
        }else if (exception instanceof InternalAuthenticationServiceException){
            resultInfo.setErrorMsg(exception.getMessage());
        }

        request.setAttribute("resultInfo",resultInfo);
        packagedData.writeValue(resultInfo,response);

    }


}
